$(function () {
    //获取url
    var url = localStorage.getItem("ajaxUrl");
    var work_id = "";
    var divideId = localStorage.getItem("divideId");
    var machine = localStorage.getItem("divideMachine");
    var work = "";
    var controlvalue_I = 2.800; //T
    var controlvalue_J = 0.500; //T
    var pass = 1;
    var focus = true;

    $(".head .icon-lishi1").on("click", function () {
        var machine = $("section span.machine").html();
        if (machine && machine != "空") {
            localStorage.setItem("divideMachine", machine);
        }
        window.location.href = "divide_lishi.html";
    });

    //搜索框 获取焦点
    $("#goods_id").focus();
    $("#goods_id").blur(function () {
        if (focus) {
            $("#goods_id").focus();
        }
    });

    //点击返回按钮
    $(".head").on("click", ".goBack", function () {
        localStorage.removeItem("divideId");
        localStorage.removeItem("divideMachine");
        window.location.href = "divide.html";
    });

    //根据 id 得到 工单信息、机台信息
    getWorkFun(machine);

    function getWorkFun(machine) {
        if (machine) {
            loading_show("获取中...");
            $.ajax({
                headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
                type: "post",
                url: url + '/app/divide/getDividePlanAndMaterialByMachine',
                data: {
                    divideId: divideId,
                    machine: machine
                },
                dataType: 'json',
                json: 'callback',
                success: function (res) {
                    loading_hide();
                    if (res.success) {
                        var data = res.result;
                        work = data.plan;
                        // if (res.controlvalue) {
                        //     if (res.controlvalue["I"]) {
                        //         controlvalue_I = res.controlvalue["I"];
                        //     }
                        //     if (res.controlvalue["J"]) {
                        //         controlvalue_J = res.controlvalue["J"];
                        //     }
                        // }
                        $("section span.machine").html(machine);
                        if (data.plan && data.plan.workplanNumber) {
                            work_id = data.plan._id;
                            $("section span.workplanNumber").html(data.plan.number);
                            $("section span.kh").html(data.plan.customerNameShort);
                            $("section span.work_gg").html(data.plan.inventorySpecification);
                            $("section span.work_orderLength").html(data.plan.orderLength);
                            $("section span.work_addLength").html(data.plan.addLength);
                        } else {
                            $("section span.workplanNumber").html("空");
                            $("section span.kh").html("空");
                            $("section span.work_gg").html("空");
                            $("section span.work_orderLength").html("空");
                            $("section span.work_addLength").html("空");
                        }
                        if (data.material && data.material.length > 0) {
                            $("section div.material span.number").html(data.material[0].batch);
                            $("section div.material span.gggh").html(data.material[0].inventorySpecification);
                            // $("section div.material span.lh").html(data.material[0].stove);
                            // $("section div.material span.column").html(data.material[0].column);
                            $("section div.material span.length").html(data.material[0].length);
                            setAllmaterial(data.material);
                            // if (Number(data.material[0].length) < 50) {
                            //     $alert("当前原料剩余米长小于50m了，请检查", 3000);
                            // }
                        } else {
                            $("section div.material span.number").html("空");
                            $("section div.material span.gggh").html("空");
                            $("section div.material span.lh").html("空");
                            $("section div.material span.column").html("空");
                            $("section div.material span.length").html("空");
                            setAllmaterial([]);
                        }
                    } else {
                        console.log(res);
                        $alert(res.message);
                    }
                },
                error: function (error) {
                    loading_hide();
                    console.log(error);
                    $alert(error.responseText);
                }
            });
        } else {
            $("section span.machine").html("空");
        }
        if (divideId) {
            $.ajax({
                headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
                type: "post",
                url: url + '/app/divide/getGobacktaskorder',
                data: {
                    divideId: divideId,
                },
                dataType: 'json',
                json: 'callback',
                success: function (res) {
                    loading_hide();
                    if (res.success) {
                        var data = res.result;
                        work = data;
                        if (data.plan && data.plan.workplanNumber) {
                            work_id = data.plan._id;
                            $("section span.workplanNumber").html(data.plan.number);
                            $("section span.kh").html(data.plan.customerNameShort);
                            $("section span.work_gg").html(data.plan.inventorySpecification);
                            $("section span.work_orderLength").html(data.plan.orderLength);
                            $("section span.work_addLength").html(data.plan.addLength);
                        } else {
                            $("section span.workplanNumber").html("空");
                            $("section span.kh").html("空");
                            $("section span.work_gg").html("空");
                            $("section span.work_orderLength").html("空");
                            $("section span.work_addLength").html("空");
                        }
                    } else {
                        console.log(res);
                        $alert(res.message);
                    }
                },
                error: function (error) {
                    loading_hide();
                    console.log(error);
                    $alert(error.responseText);
                }
            });
        }
    }

    $("#goods_id").on("keydown", function (event) {
        if (event.keyCode == "13") {
            if (pass == 0) {
                return
            }
            pass = 0;
            var val = $(this).val();
            $("#goods_id").val("");
            if (!val) {
                $alert("请扫描回倒机台！");
                pass = 1;
                setTimeout(function () {
                    $("#goods_id").val("").focus();
                }, 1400);
                return;
            } else {
                $.ajax({
                    headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
                    type: "post",
                    url: url + '/app/divide/getDividePlanAndMaterialByMachine',
                    data: {
                        divideId: divideId,
                        machine: val
                    },
                    dataType: 'json',
                    json: 'callback',
                    success: function (res) {
                        pass = 1;
                        loading_hide();
                        if (res.success) {
                            var data = res.result;
                            $alert(val + "扫描成功");
                            work = data.plan;
                            // if (res.controlvalue) {
                            //     if (res.controlvalue["I"]) {
                            //         controlvalue_I = res.controlvalue["I"];
                            //     }
                            //     if (res.controlvalue["J"]) {
                            //         controlvalue_J = res.controlvalue["J"];
                            //     }
                            // }
                            //填充 当前机台与当前用料
                            $("section span.machine").html(val);
                            /*if (data.plan && data.plan.workplanNumber) {
                                work_id = data.plan._id;
                                $("section span.workplanNumber").html(data.plan.number);
                                $("section span.kh").html(data.plan.customerNameShort);
                                $("section span.work_gg").html(data.plan.inventorySpecification);
                                $("section span.work_orderLength").html(data.plan.orderLength);
                                $("section span.work_addLength").html(data.plan.addLength);
                            } else {
                                $("section span.workplanNumber").html("空");
                                $("section span.kh").html("空");
                                $("section span.work_gg").html("空");
                                $("section span.work_orderLength").html("空");
                                $("section span.work_addLength").html("空");
                            }*/
                            if (data.material && data.material.length > 0) {
                                $("section div.material span.number").html(data.material[0].batch);
                                $("section div.material span.gggh").html(data.material[0].inventorySpecification);
                                // $("section div.material span.lh").html(data.material[0].stove);
                                // $("section div.material span.column").html(data.material[0].column);
                                $("section div.material span.length").html(data.material[0].length);
                                setAllmaterial(data.material);
                                // if (Number(data.material[0].length) < 50) {
                                //     $alert("当前原料剩余米长小于50m了，请检查", 3000);
                                // }
                            } else {
                                $("section div.material span.number").html("空");
                                $("section div.material span.gggh").html("空");
                                $("section div.material span.lh").html("空");
                                $("section div.material span.column").html("空");
                                $("section div.material span.length").html("空");
                                setAllmaterial([]);
                            }
                        } else {
                            console.log(res);
                            $alert(res.message);
                        }
                    },
                    error: function (error) {
                        pass = 1;
                        loading_hide();
                        console.log(error);
                        $alert(error.responseText);
                    }
                });
            }
        }
    });

    function setAllmaterial(material) {
        // console.log(material.length)
        var allMaterialHtml = "";
        for (var i = 1; i < material.length; i++) {
            allMaterialHtml += '  <div class="card-content-inner">' +
                '<p><span>编&#X3000;&#X3000;号 ：</span><span class="number">' + material[i].batch + '</span></p>' +
                '<p><span>规格钢号 ：</span><span class="gggh">' + material[i].inventorySpecification + '</span></p>' +
                // '<p><span>炉号 ：</span><span class="lh">' + material[i].stove + '</span>&nbsp;&nbsp;<span>卷号 ：</span><span class="column">' + material[i].column + '</span></p>' +
                '<p><span>剩余米长 ：</span><span class="length">' + material[i].length + '</span></p></div>'
        }
        $(".allMaterial").empty().html(allMaterialHtml).hide();
    }

    // 点击 下箭头
    $(".material").on("click", ".aaa", function (event) {
        var classname = $(this).attr("class");
        if (classname.indexOf("icon-xiashuangjiantou") > -1) {
            $(".allMaterial").show();
            $(this).removeClass("icon-xiashuangjiantou");
            $(this).addClass("icon-shangshuangjiantou");

        } else{
            $(".allMaterial").hide();
            $(this).removeClass("icon-shangshuangjiantou");
            $(this).addClass("icon-xiashuangjiantou");
        }
    });
    //点击 上料
    $(".bnt .shangliao").on("click", function () {
        var machine = $("section span.machine").html();
        if (!machine || machine == "空") {
            $alert("请先扫描回倒机台");
            setTimeout(function () {
                $("#goods_id").val("").focus();
            }, 1400);
        } else {
            loading_show("获取中...");
            $.ajax({
                headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
                type: "post",
                url: url + '/app/divide/isFeedMachine',
                dataType: 'json',
                data: {
                    id: work_id,
                    machine: $("section span.machine").html()
                },
                json: 'callback',
                cache: false,
                timeout: 60000,
                success: function (res) {
                    if (res.success) {
                        var data = res.result;
                        loading_hide();
                        // var weight = $("section .material span.weight").html();
                        // //if (weight != "空" && Number(weight) > 500) return $alert("剩余重量大于500，不可上料");
                        // localStorage.setItem("work_id", work_id);
                        // localStorage.setItem("divideMachine", machine);
                        // window.location.href = "divide_sl.html";
                        localStorage.setItem("work_id", work_id);
                        localStorage.setItem("divideMachine", machine);
                        window.location.href = "divide_sl.html";
                    } else {
                        console.log(res);
                        $alert(res.message);
                    }
                },
                error: function (error) {
                    //隐藏提示符 显示
                    loading_hide();

                    if (error.status == 0) {
                        $alert("请求超时，请再试一次！");
                    } else {
                        console.log(error);
                        $alert(error.responseText);
                    }
                }
            });
        }
    });

    // 点击 清楚 原料
    $(".bnt .clear").on("click", function () {
        var machine = $("section span.machine").html();
        var workplanNumber = $("section span.workplanNumber").html();
        var quantity = $("section div.material span.length").html();
        var number = $("section div.material span.number").html();
        // if (!workplanNumber || workplanNumber == "空") {
        //     return $alert("请先扫描机台号");
        // }
        if (!machine || machine == "空") {
            $alert("请先扫描回倒机台");
        } else {
            $.confirm("当前用料剩余" + quantity + "m，确认清除吗？", function () {
                loading_show("清除中...");
                $.ajax({
                    headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
                    type: "post",
                    url: url + '/app/divide/clearMachinematerial',
                    dataType: 'json',
                    data: {
                        id: work_id,
                        batch: number,
                        machine: machine
                    },
                    json: 'callback',
                    cache: false,
                    timeout: 60000,
                    success: function (res) {
                        if (res.success) {
                            var data = res.result;
                            loading_hide();
                            $alert("清除成功");
                            localStorage.setItem("divideMachine", machine);
                            setTimeout(function () {
                                window.location.href = "divide_one.html";
                            }, 1200);
                        } else {
                            console.log(res);
                            $alert(res.message);
                        }
                    },
                    error: function (error) {
                        //隐藏提示符 显示
                        loading_hide();

                        if (error.status == 0) {
                            $alert("请求超时，请再试一次！");
                        } else {
                            console.log(error);
                            $alert(error.responseText);
                        }
                    }
                });
            })
        }
    });

    //点击 退料
    $(".bnt .returnMaterial").click(function () {
        if ($("div.material span.number").html() && $("div.material span.number").html() != "空") {
            focus = false;
            $(".mengceng").show();
            $("div.div_tuiliao").show();
            $("div.div_tuiliao input.symc").val("").focus();
        } else {
            $alert("请先上料！");
        }
    });
    //点击 退料 取消
    $("div.div_tuiliao .tl_quxiao").click(function () {
        $(".mengceng").hide();
        $("div.div_tuiliao").hide();
        $("#goods_id").focus();
        focus = true;
    });
    //点击 退料 确定
    $("div.div_tuiliao .tl_queding").click(function () {
        if ($("div.div_tuiliao input.symc").val() <= 0) {
            $alert("剩余米长应大于零");
            $("div.div_tuiliao input.symc").focus();
        } else {
            //调用 收线 接口
            loading_show("退料中...");
            //拉丝 收线
            $.ajax({
                headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
                type: "post",
                url: url + '/app/divide/divideReturnMaterial',
                data: {
                    id: work_id,
                    batch: $("section span.number").html(),
                    machine: $("section span.machine").html(),
                    aLength: $("div.div_tuiliao input.symc").val()
                },
                dataType: 'json',
                json: 'callback',
                success: function (res) {
                    if (res.success) {
                        var data = res.result;
                        console.log(data);
                        loading_hide();
                        $alert("退料成功");
                        var machine = $("section span.machine").html();
                        localStorage.setItem("divideMachine", machine);
                        setTimeout(function () {
                            window.location.href = "divide_one.html";
                        }, 1200);
                    } else {
                        console.log(res);
                        loading_hide();
                        $alert(res.message);
                    }
                },
                error: function (error) {
                    console.log(error);
                    loading_hide();
                    $alert(error.responseText);
                }
            });
        }
    });

    // 点击 收线
    $(".bnt .shouxiao").on("click", function (event) {
        // var workplanNumber = $("section span.workplanNumber").html();
        var machine = $("section span.machine").html();
        if (!machine || machine == "空") {
            return $alert("请先扫描机台号");
        }
        if ($("div.material span.number").html() && $("div.material span.number").html() != "空") {
            focus = false;
            $(".mengceng").show();
            $("div.div_shouxian").show();
            $("div.div_shouxian select").val("合格").trigger("change");
            $("div.div_shouxian select.isShort").val("否").trigger("change");
            //$("div.div_shouxian select.cppz").val("").trigger("change");
            $("div.div_shouxian input").val("");
            $("div.div_shouxian input.cpmc").val("").focus();
            $("div.div_shouxian input.disctool").val(work.disctool || "");
        } else {
            $alert("请先上料！");
        }
    });
    //点击 收线 取消
    $(".sx_quxiao").click(function () {
        $(".mengceng").hide();
        $("div.div_shouxian").hide();
        $("#goods_id").val("").focus();
        focus = true;
    });
    var qualityJson = {
        zj: "",
        bmzl: ""
    };
    $(".sx_queding").click(function () {
        if (pass == 0){
            return
        }
        pass = 0;
        if (!$("div.div_shouxian input.cpmc").val()) {
            pass=1;
            $alert("请输入米长");
            $("div.div_shouxian input.cpmc").focus();
        } else if ($("div.div_shouxian input.cpmc").val() <= 0 ) {
            pass=1;
            $alert("米长不可小于0");
            $("div.div_shouxian input.cpzl").focus();
        }  else if (!$("div.div_shouxian select.isShort").val()) {
            pass=1;
            $alert("请选择是否短尺");
        } else {
            if ($("div.div_shouxian .bmzl").val() == "不合格") {
                qualityJson.bmzl = "表面质量不合格";
            } else {
                qualityJson.bmzl = "";
            }
            var bhgx = [];
            for (var k in qualityJson) {
                if (qualityJson[k]) {
                    bhgx.push(qualityJson[k]);
                }
            }

            // var shouxianWeight = Number(setWeight(zj, $("div.div_shouxian input.cppz").val()));
            // var work_weight = $("section span.work_weight").html();
            // var work_completeWeight = accAdd(($("div.div_shouxian select.selfResult").val() == "合格" ? Number(shouxianWeight) : 0), $("section span.work_completeWeight").html());
            // var chazhi = accSub(work_completeWeight, work_weight);
            //调用 收线 接口
            loading_show("收线中...");
            //自动完工
            $.ajax({
                headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
                type: "post",
                url: url + '/app/divide/divideTakeup',
                data: {
                    _id: divideId,
                    machine: $("section span.machine").html(),
                    // weight: $("div.div_shouxian input.cpzl").val(),
                    // tare_weight: $("div.div_shouxian input.cppz").val(),
                    length: $("div.div_shouxian input.cpmc").val(),
                    breakpoint: $("div.div_shouxian input.breakpoint").val(),
                    bmzl: $("div.div_shouxian .bmzl").val(),
                    selfResult: $("div.div_shouxian .selfResult").val(),
                    isShort: $("div.div_shouxian .isShort").val(),
                    disctool: $("div.div_shouxian .disctool").val(),
                    bhgx: JSON.stringify(bhgx),
                    printAmount: 1
                },
                dataType: 'json',
                json: 'callback',
                success: function (res) {
                    pass=1;
                    if (res.success) {
                        //console.log(data);
                        loading_hide();
                        $alert("收线成功");
                        localStorage.setItem("divideMachine", $("section span.machine").html());
                        setTimeout(function () {
                            window.location.href = "divide_one.html";
                        }, 1200);
                        //24.12.12 回倒 打印标签 改成 合绳模板
                        takeupPrint("uniteWire", res.result);
                    } else {
                        console.log(res);
                        loading_hide();
                        $alert(res.message);
                    }
                },
                error: function (error) {
                    pass=1;
                    console.log(error);
                    loading_hide();
                    $alert(error.responseText);
                }
            });
        }
    });

    //皮重 毛重 失去 焦点 则 计算 净重
    $("div.div_shouxian").on("input", "input.cpzl", function () {
        setCpjz();
    });
    $("div.div_shouxian").on("input", "input.cppz", function () {
        setCpjz();
    });

    //计算 毛重
    function setCpjz() {
        var mz = $("div.div_shouxian input.cpzl").val();
        var pz = $("div.div_shouxian input.cppz").val();
        if (mz == "") {
            return;
        } else {
            if (pz == "") {
                pz = 0;
            }
            $("div.div_shouxian input.cpjz").val(accSub(mz, pz));
        }
    }

});
